import requests
import json
from bisheng.api.jsj_api.model.metro_fault import MetroFault
from bisheng.api.jsj_api.model.metro_fault_task import MetroFaultTask, MetroFaultTaskDao, StatusEnum
from uuid import UUID
from typing import List, Optional
from datetime import datetime, timedelta
from .config_service import ConfigService
from .equipment_service import MaintenanceRuleService


class TaskService:

    def init_task_by_metro_fault(self, metro_fault,maintenance_rule,start_time: str, end_time: str = None):
        """初始化task，时间为周期参数计算而来"""
        if end_time is None:
            current_time = datetime.now()
            end_time = current_time.strftime("%Y-%m-%d %H:%M:%S")

        print(metro_fault)
        task = MetroFaultTask(
            equipment_id=metro_fault.equipment_id,
            metro_fault_id=str(metro_fault.id),
            suggestion_start_time=start_time,
            suggestion_end_time=end_time,
            status=StatusEnum.STARTED.value,
            suggestion="",
            maintenance_standard=maintenance_rule.maintenance_standard,
            strategy_name=maintenance_rule.strategyName,
            strategy_number=maintenance_rule.strategyNumber,
        )
        print(task)
        return self.create_task(task)

    @staticmethod
    def create_task(task: MetroFaultTask) -> MetroFaultTask:
        """
        创建新的地铁故障任务
        """

        # # 创建 MetroFaultTask 对象
        # task = MetroFaultTask(
        #     metro_fault_id=task_data.get('metro_fault_id'),
        #     equipment_id=task_data.get('equipment_id', ''),
        #     suggestion_start_time=task_data.get('suggestion_start_time'),
        #     suggestion_end_time=task_data.get('suggestion_end_time'),
        #     suggestion=task_data.get('suggestion', ''),
        #     status=task_data.get('status', StatusEnum.STARTED.value)
        # )

        # 使用 DAO 创建任务
        return MetroFaultTaskDao.create_task(task)

    @staticmethod
    def update_task(id: UUID, update_data: dict) -> Optional[MetroFaultTask]:
        """
        更新地铁故障任务
        """
        # 使用 DAO 更新任务
        return MetroFaultTaskDao.update_task(id, update_data)

    @staticmethod
    def search_tasks(search_data: dict) -> List[MetroFaultTask]:
        """
        搜索地铁故障任务
        """
        # 使用 DAO 搜索任务
        return MetroFaultTaskDao.search_tasks(search_data.get('metro_fault_id'),
                                              search_data.get('equipment_id'),
                                              search_data.get('suggestion_start_time'),
                                              search_data.get('suggestion_end_time'),
                                              search_data.get('status'))

    def post_suggestion_by_task(self, metro_fault: MetroFault, metro_fault_tasks: List[MetroFaultTask]):
        print("post_suggestion_by_task")
        url = ConfigService().get_config_by_key("post_suggestion_url").value

        json_data = self.assemble_post_body(metro_fault, metro_fault_tasks)
        headers = {
            'Content-Type': 'application/json'
        }
        print(json_data)
        response = requests.post(url, json=json_data, headers=headers)
        print(response.text)
        if response.status_code == 200:
            for task in metro_fault_tasks:
                task.status = StatusEnum.COMPLETED.value
                MetroFaultTaskDao.update_self(task)
        else:
            for task in metro_fault_tasks:
                task.status = StatusEnum.FAILED.value
                task.error_msg = response.text
                MetroFaultTaskDao.update_self(task)
        return metro_fault_tasks

    @staticmethod
    def assemble_post_body(metro_fault: MetroFault, metro_fault_tasks: List[MetroFaultTask]):
        # 创建要发送的 JSON 数据
        messages = []
        for metro_fault_task in metro_fault_tasks:
            message = {
                "equipment_id": metro_fault.equipment_id,
                "equipment_name": metro_fault.equipment_name,
                "suggestion": metro_fault_task.suggestion,
                "line": metro_fault.line,
                "level": metro_fault_task.level,
                "strategyName":metro_fault_task.strategy_name,
                "strategyNumber":metro_fault_task.strategy_number,
            }
            messages.append(message)
        post_data = {
            "messages": messages
        }

        json_data = json.dumps(post_data, ensure_ascii=False)
        return json_data

    @staticmethod
    def get_suggestion_by_equipment_id(equipment_id: str):
        task = MetroFaultTaskDao.get_first_by_equipment_id_and_non_zero_status(equipment_id)
        if task is None:
            return None
        return task.suggestion

    def create_tasks_by_metro_fault(self, metro_fault: MetroFault):
        maintenance_rules = MaintenanceRuleService().get_by_equipment_id(metro_fault.equipment_id)
        if maintenance_rules is None:
            print("未查询到对应的标准规则：", metro_fault.equipment_id)
            return None
        now_time: datetime = datetime.now()
        task_list = []
        for maintenance_rule in maintenance_rules:
            print(now_time)
            data_time = MaintenanceRuleService().get_start_time_by_maintenance_rule(maintenance_rule,now_time)
            print(data_time)
            task = self.init_task_by_metro_fault(metro_fault, maintenance_rule,start_time=data_time.strftime("%Y-%m-%d %H:%M:%S"),
                                                 end_time=now_time.strftime("%Y-%m-%d %H:%M:%S"))
            task_list.append(task)

        return task_list

    @staticmethod
    def get_tasks_by_equipment_id(equipment_id:str):
        return MetroFaultTaskDao.get_by_equipment_id(equipment_id)



